<!--
 * @Author: 18970328563 2726167793@qq.com
 * @Date: 2023-02-04 22:36:46
 * @LastEditors: 18970328563 2726167793@qq.com
 * @LastEditTime: 2023-02-06 23:17:59
 * @FilePath: \demo_lan\vue_demo\src\view\ScrollAnimation.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="box" @scroll="testThrottleFn">
    <h3>Scroll to see the animation</h3>
    <div class="scroll" v-for="(item,index) in 12" :key="index">Content</div>
  </div>
</template>
<script setup>
import { onMounted } from 'vue';
//获取盒子距离顶部的高度
const move = () => {
  //获取浏览器的当前可视高度
  const winHight = (window.innerHeight / 5) * 4;
  // console.log(winHight,'获取浏览器的当前可视高度');
  //要想获取盒子距离顶部的高度，首先要获取所有的dom节点
  const scrollDivs = document.querySelectorAll('.scroll')
  // console.log(scrollDivs);
  scrollDivs.forEach(item=>{
    //获取盒子距离顶部的高度
    const scrollHight = item.getBoundingClientRect().top
    item.classList.remove('move')
    //如果盒子距离顶部的高度小于浏览器的当前可视高度，那么就添加class效果
    if(scrollHight<winHight){
      item.classList.add('move')
    }
  })
}
//封装的节流方法
function throttle(fn, delay) {
  let previous = 0;
  // 使用闭包返回一个函数并且用到闭包函数外面的变量previous
  return function() {
      let args = arguments;
      let now = new Date();
      if(now - previous > delay) {
          fn.apply(this, args);
          previous = now;
      }
  }
}
let testThrottleFn = throttle(move, 80); // 节流函数
//因为监听的是滚动事件，所以要先执行一次
onMounted(function() {
  move();
})

</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  background-color: #efedd6;
  text-align: center;
  overflow: auto;
}

h3 {
  font-size: 30px;
  margin-top: 10px;
}

.scroll {
  background-color: steelblue;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 400px;
  height: 200px !important;
  margin: 10px;
  border-radius: 10px;
  box-shadow: 2px 4px 5px rgb(0 0 0 / 30%);
  margin: 20px auto;
  font-size: 40px;
  font-weight: 600;
  transform: translateX(400%);
  transition: all .3s;
}

.scroll:nth-child(even) {
  transform: translateX(-400%);
}

.box .move {
  transform: translateX(0);
}
</style>